var Faye = require('faye')
var HOST = '0.0.0.0';     //定义服务器地址
var client = new Faye.Client('http://' + HOST + ':3344/events');
var comn = require('../../algo/routes/comn');
var fs = require("fs");


require('./mock_client1')
require('./mock_client2')
require('./mock_client3')
require('./mock_client146')
require('./mock_client147')

console.log("BASE  BASE");
var data = {};
var timeNum = {
    "$GNGGA": 1,
    "$PASHR": 4,
    "$PASHD": 2,
    "$PTNL": 2,
    "$GPGGA": 1
};

var ggaStatus = ['', 'single', 'dgps', '', 'fix', 'float'];
var posStatus = ['', 'single', 'fix', 'float'];

var TIME = 1;
var l = 0;

client.subscribe('/station', function (message) {
    // console.log(message.id+":"+new Date().toLocaleTimeString())
    var baseCurrentTime;
    var currentTime;
    if (message.data.indexOf("GGA") !== -1) {
        var gga = message.data.split('\r\n')
        var line = gga[0].split(',');
        baseCurrentTime = line[timeNum[line[0]]];
        if (!data[baseCurrentTime]) {
            data[baseCurrentTime] = {};
        }
        data[baseCurrentTime][message.id] = {pos: line};

        // console.log(baseCurrentTime+'--------' + message.id)

        // fs.appendFile('./base/7_18' + message.id + '.txt', message.data + '\n', function (err) {
        //     if (err) throw err;
        //     //数据被添加到文件的尾部
        //     console.log(message.id+':appended to file!');
        // });
    }
    if (message.id == '8147' || message.id == '8146') {
        var lines = message.data.split('\r\n')
        var key;

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i].split(',');
            if (line.length < 5) {
                continue;
            }

            currentTime = line[timeNum[line[0]]];
            if (!data[currentTime]) {
                data[currentTime] = {};
            }
            if (!data[currentTime][message.id + "#1"]) {
                data[currentTime][message.id + "#1"] = {pos: [], avr: []};
            }
            if (!data[currentTime][message.id + "#2"]) {
                data[currentTime][message.id + "#2"] = {pos: [], avr: []};
            }

            if (line[4].indexOf("BEG*") !== -1) {
                key = line[1];
                continue
            }
            if (line[1] === "POS") {
                data[currentTime][message.id + key].pos = line;
                continue
            }
            if (line[1] === "AVR") {
                data[currentTime][message.id + key].avr = line;
            }
        }
        // console.log(currentTime+'--------' + message.id)
        // fs.appendFile('./rover/7_18' + message.id + '.txt', message.data + '\\\n', function (err) {
        //     if (err) throw err;
        //     //数据被添加到文件的尾部
        //     console.log(message.id+':appended to file!');
        // });
    }
})


function sortTime(a, b) {
    return b - a
}

var set = setInterval(function () {
    var length = Object.keys(data).sort(sortTime);

    for (var i = 0; i < length.length; i++) {
        var keys = data[length[i]];
        if (Object.keys(keys).length === 7) {
            var info = keys;

            var postlist = {}
            for (var key in info) {


                postlist[key] = []
                if (key.indexOf('#') === -1) {
                    postlist[key] = [getDegrees(info[key].pos[2]), getLongitude(info[key].pos[4]),
                        Number(info[key].pos[9]) + Number(info[key].pos[11]), key];
                } else {
                    postlist[key] = [getDegrees(info[key].pos[5]), getLongitude(info[key].pos[7]),
                        Number(info[key].pos[9]), key]
                }
            }
            comn.pos2ecef(postlist, function (data) {
                // data.updateTime = new Date().getTime();
                client.publish('/node', {
                    data: data,
                    updateTime: new Date().getTime()
                })
            })

            break
        }

    }

    l++;
    // if (l === Object.keys(data).length) {
    //     clearInterval(set)
    // }
    if (length.length > 30) {
        delete  data[length[length.length - 1]];
    }
}, 1000);


function getDegrees(data) {
    if (!data) {
        return
    }
    var branch = Number(data.substring(0, 2));
    var degree = Number(data.substr(2));
    return (branch + degree / 60) * Math.PI / 180
}

function getLongitude(data) {
    if (!data) {
        return
    }
    var branch = Number(data.substring(0, 3));
    var degree = Number(data.substr(3));
    return (branch + degree / 60) * Math.PI / 180
}